﻿using System;
using System.Collections.Concurrent;
using ServiceStack.Redis;
namespace ExpressManagement.Areas.BackSys.ServiceTools.Redis
{
  
    public class RedisHelper
    {

        private static readonly object LockObj = new object();
        private static RedisHelper _instance;
        public static int ExpireSeconds { get; private set; }
        private static RedisClient _redisClient;

        //连接字符串
        private static string _connectionString;
        //实例名称
        private static string _instanceName;
        //默认数据库
        private static int _defaultDB;
        public static RedisHelper Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (LockObj)
                    {
                        if (_instance == null)
                            _instance = new RedisHelper(_connectionString, _instanceName, _defaultDB);
                    }
                }

                return _instance;
            }
        }


    


        //private ConcurrentDictionary _connections;

        public RedisHelper(string connectionString, string instanceName, int defaultDB = 0,int expireseconds=3600)
        {
            _connectionString = connectionString;
            _instanceName = instanceName;
            _defaultDB = defaultDB;
            ExpireSeconds = expireseconds;
            try
            {
                var splits = _connectionString.Split(':');
                var host = splits[0];
                int port = Convert.ToInt32(splits[1]);
                var pwd = "";
                if (string.IsNullOrWhiteSpace(host) || port <= 0)
                    throw new ArgumentNullException("配置文件中未找到RedisServer的有效配置");

                _redisClient = new RedisClient(host, port);
                if (!string.IsNullOrWhiteSpace(pwd))
                {
                    _redisClient.Password = pwd;
                    //_redisClient.Db= 0;
                }
                _redisClient.RemoveAll(_redisClient.GetAllKeys());

            }
            catch (Exception ex)
            {
                //Logger.GetLogger(this.GetType()).ErrorFormat("Redis出现异常，\r\n 异常消息：{0}", ex.Message);
            }
        }


        /// <summary>
        /// 写入
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public bool Insert<T>(string key, T t)
        {
            try
            {
                return _redisClient.Set(key, t);
            }
            catch (Exception ex)
            {
                //Logger.GetLogger(this.GetType()).ErrorFormat("Redis出现异常，\r\n 异常消息：{0}", ex.Message);
            }

            return false;
        }

        /// <summary>
        /// 写入
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="t"></param>
        /// <param name="expireSeconds">过期时间 秒</param>
        /// <returns></returns>
        public bool Insert<T>(string key, T t, int expireSeconds)
        {
            try
            {
                var r = _redisClient.Set(key, t);
                if (r)
                {
                    _redisClient.Expire(key, expireSeconds); //设置指定Key的过期时间
                }
            }
            catch (Exception ex)
            {
                //Logger.GetLogger(this.GetType()).ErrorFormat("Redis出现异常，\r\n 异常消息：{0}", ex.Message);
            }

            return false;
        }

        /// <summary>
        /// 读取
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T Get<T>(string key)
        {
            try
            {
                return _redisClient.Get<T>(key);
            }
            catch (Exception ex)
            {

                //Logger.GetLogger(this.GetType()).ErrorFormat("Redis出现异常，\r\n 异常消息：{0}", ex.Message);
            }
            return default(T);
        }

        /// <summary>
        /// 从缓存中移除指定键的缓存值
        /// </summary>
        /// <param name="key"></param>
        public void Remove(string key)
        {
            _redisClient.Remove(key);
        }

        /// <summary>
        /// 从缓存中移除指定键的缓存值
        /// </summary>
        /// <param name="pattern"></param>
        public void RemoveByPattern(string pattern)
        {
            var keys = _redisClient.SearchKeys(pattern + "*");

            if (keys != null && keys.Count > 0)
                _redisClient.RemoveAll(keys);
        }
    }

}
